具有多个不相关表的SQL查询

时间:2016-08-12 11:50:37

标签: mysql sql-server select multiple-tables multiple-conditions

在我的mySQL数据库中有四个表:breakfastdinnersuppersupper。 这些表的列名是相同的。其中每个人都有一个名为“accepted”的列,该列等于01

我想让SQL查询从这四个表中给出一个随机行 WHERE'已接受'列等于0。

只有1个表有效的SQL查询:

SELECT * FROM breakfast WHERE accepted=0 ORDER BY RAND() LIMIT 1

我的SQL查询版本有四个不起作用的表:

 SELECT * FROM breakfast, dinner, supper, dessert WHEREbreakfast.accepted=0
AND dinner.accepted=0 AND supper.accepted=0 AND dessert.accepted=0 ORDER BY RAND() LIMIT 1

3 个答案:

答案 0 :(得分:0)

试试这个,

我假设所有四个表中的列数相同。

的MySQL

   SELECT col1,col2
FROM (
    SELECT col1,col2
    FROM breakfast
    WHERE breakfast.accepted = 0

    UNION

    SELECT col1,col2
    FROM dinner
    WHERE dinner.accepted = 0

    UNION

    SELECT col1,col2
    FROM supper
    WHERE supper.accepted = 0

    UNION

    SELECT col1,col2
    FROM dessert
    WHERE dessert.accepted = 0
    ) T
ORDER BY RAND() LIMIT 1

SQL Server:

SELECT top 1 col1,col2
FROM (
    SELECT col1,col2
    FROM breakfast
    WHERE breakfast.accepted = 0

    UNION

    SELECT col1,col2
    FROM dinner
    WHERE dinner.accepted = 0

    UNION

    SELECT col1,col2
    FROM supper
    WHERE supper.accepted = 0

    UNION

    SELECT col1,col2
    FROM dessert
    WHERE dessert.accepted = 0
    ) T
ORDER BY newid()

答案 1 :(得分:0)

试试这个:

//

在这个查询中,除了表早餐中有一个名字早餐的字段,如果你需要使用" *"请使用别名使所有字段名称在不同的联合查询中相似。

答案 2 :(得分:0)

检查

 SELECT TOP 1 * FROM breakfast,
 (SELECT TOP 1 * FROM dinner WHERE accepted=0 ORDER BY RAND()) As Dinner,
 (SELECT TOP 1 * FROM supper WHERE accepted=0 ORDER BY RAND()) As supper,
 (SELECT TOP 1 * FROM dessert WHERE accepted=0 ORDER BY RAND()) As dessert 
 WHERE breakfast.accepted=0 ORDER BY RAND()