Select First Row In Each Group MySQL

Select the First Row In Each Group of MySQL Here is an example: SELECT MIN(purchases2.id), # change to MAX if you want the highest value purchases1.customer, purchases1.total FROM PURCHASES purchases1 JOIN (SELECT p.customer, MAX(total) AS max_total FROM PURCHASES purchases GROUP BY p.customer) purchases2 ON purchases2.customer = purchases1.customer AND purchases2.max_total = purchases1.total GROUP BY purchases1.customer, purchases1.total

Alter Table if Column Not Exist in MySQL

Alter Table if Column Not Exist in MySQL To alter the table if the column does not exist: IF NOT EXISTS( SELECT NULL FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ‘tableName’ AND table_schema = ‘database_name’ AND column_name = ‘columnName’) THEN ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default ‘0’; END IF;

Concatenate Multiple Rows Into One Field MySQL

GROUP_CONCAT function is used to concatenate multiple rows into a single field in MySQL. SELECT student_id, GROUP_CONCAT(subject_name SEPARATOR ‘, ‘) FROM student_subject GROUP BY student_id; Distinct Operator can be used to avoid duplicates. SELECT student_id, GROUP_CONCAT(distinct subject_name SEPARATOR ‘, ‘) FROM student_subject GROUP BY student_id; Order By Clause can be used to keep the values … Read more

Find All Tables in MySQL With Specific Column Names

Find All Tables in MySQL With Specific Column Names in specific schema. SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN (‘columnName1′,’columnName2′, columnNameN) AND TABLE_SCHEMA=’Database Name’; Find All Tables in MySQL With Specific Column Names in all schemas. SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME IN (‘columnName1′,’columnName2’, columnNameN)

Get All Columns in MySQL

Get all Column of a specific Tables in MySQL. SELECT table_name as ‘Table Name’, column_name as ‘Column Name’ FROM information_schema.COLUMNS WHERE table_schema = ‘$DATABASE_NAME’; AND table_name = ‘$TABLE_NAME’; Get all Column of some Tables in MySQL. SELECT table_name as ‘Table Name’, column_name as ‘Column Name’ FROM information_schema.COLUMNS WHERE table_schema = ‘$DATABASE_NAME’; AND table_name in (‘$TABLE_NAME1’, … Read more

Get Record Count of Tables in MySQL

Get Record Count of a specific Table in MySQL. SELECT SUM(TABLE_ROWS) as ‘Total Record Count’ FROM information_schema.TABLES WHERE table_schema = ‘$DATABASE_NAME’ AND table_name = ‘$TABLE_NAME’; Get Record Count of all Tables of a specific schema in MySQL. SELECT SUM(TABLE_ROWS) as ‘Total Record Count’ FROM information_schema.TABLES WHERE table_schema = ‘$DATABASE_NAME’; Get Record Count of all Tables … Read more