将两个SELECT查询与UNION结合使用,其中一个是JOIN

时间:2018-11-02 19:33:12

标签: sql select union

我想使用UNION合并两个select语句,但是它不起作用。

$sql = "SELECT content
    FROM tbl_jokes 
    JOIN tbl_jokes_relationships ON tbl_jokes_relationships.rid_jokes = tbl_jokes.id_jokes
    WHERE tbl_jokes_relationships.rid_jokes_categories ='1'
    ORDER BY id_jokes DESC
    UNION
    SELECT * FROM tbl_jokes 
    WHERE rid_jokes_categories='blondinenwitze'
";

它不起作用,我在没有UNION的情况下测试了两个select语句,并且显示了我想要的结果,谢谢您的帮助

1 个答案:

答案 0 :(得分:3)

您需要选择相同的列。像这样:

SELECT j.*
FROM tbl_jokes j JOIN
     tbl_jokes_relationships jr
     ON jr.rid_jokes = j.id_jokes
WHERE jr.rid_jokes_categories = 1
UNION
SELECT j.*
FROM tbl_jokes j
WHERE j.rid_jokes_categories = 'blondinenwitze'

为此使用union似乎很愚蠢,除非它满足某些性能目标:

SELECT j.*
FROM tbl_jokes j LEFT JOIN
     tbl_jokes_relationships jr
     ON jr.rid_jokes = j.id_jokes
WHERE jr.rid_jokes_categories = 1 OR
      j.rid_jokes_categories = 'blondinenwitze';

请注意,子查询中的ORDER BY不会执行任何操作。如果要对结果进行排序,则必须为最外面的ORDER BY指定SELECT