MySQL - 并行合并两个不相关的查询与相同的行数

时间:2014-11-06 17:51:33

标签: mysql

我有两张桌子:

exam_outline_items:

Query Table One

jml_quiz_pool:

Query Table Two

在我尝试的所有事情中,这让我最接近:

select t1.sequence, t1.title, t2.q_cat, t2.q_count
from student_pl.exam_outline_items t1
cross join pe_joomla.jml_quiz_pool t2
where t1.exam_outline_id = 5 and t1.chapter_num > 0
    and t2.q_id = 1109 and t2.q_count > 0
group by title

产生这个结果:

Query Results from 3rd query

我只需要那些q_cat值不同,就像它们在第二个查询中一样。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

你必须要有一些东西来连接它们。如果您没有这样的列,可以通过创建带变量的rownumber来模拟一列。

select sequence, title, q_cat, q_count from (
    select t1.sequence, t1.title, @r1 := @r1 + 1 as rownumber
    from student_pl.exam_outline_items t1
    , (select @r1 := 0) var_init
    where t1.exam_outline_id = 5 and t1.chapter_num > 0
    order by t1.sequence
) a
inner join
(
    select t2.q_cat, t2.q_count, @r2 := @r2 + 1 as rownumber
    from pe_joomla.jml_quiz_pool t2
    , (select @r2 := 0) var_init
    where t2.q_id = 1109 and t2.q_count > 0
    order by t2.q_cat
) b on a.rownumber = b.rownumber;

另请注意,我在这些查询中使用了order by。在数据库中,除非您使用order by明确设置,否则您没有排序顺序。