MySQL GROUP & COUNT Multiple tables

后端 未结 2 831
星月不相逢
星月不相逢 2021-01-25 17:59

I have a 3 part problem thats been giving me trouble I know how to get the tables to work if I query 1 table at a time but I can\'t seem to figure out how I can combine both th

2条回答
  •  臣服心动
    2021-01-25 18:38

    You can use UNION to add together the results sets from two queries iff those queries return rows with the same structure (that is, if the first column in the first query is an int, then the first column in the second query must be an int, and so on). Read all about it in http://dev.mysql.com/doc/refman/5.1/en/union.html

    Once you've written the two selects and joined them with a UNION statement, you can use that as a subquery for GROUP BY or other things:

    SELECT * FROM (
    (SELECT 1 AS ticked, col1, col2 FROM table1 INNER JOIN table2 USING (col3))
        UNION
    (SELECT 0 AS ticked, col1, col2 FROM table1)
    ) AS combined_table /*derived tables need a unique name*/
    GROUP BY col1 /*group by the unique col1 to stop duplicates*/
    ORDER BY ticked DESC
    

提交回复
热议问题