在一个查询中选择两次并在哪里

时间:2016-10-13 08:37:54

标签: mysql

我的查询有问题。

我的查询视图如下:

SELECT 
            Tab1.`name`,
            Tab1.`removed`,
            Raq.`removed`,
            Raq.`type`,
            (select `value` from `raq_add` where `raq_id` = `Tab1`.`raq_id` and `key` = 'v') as `v`

FROM `reservation` `Reservation`
            left join `tab1` `Tab1` on `Tab1`.`id` = `Reservation`.`tab1_id`
            left join `raq` `Raq` on `Raq`.`id` = `Tab1`.`raq_id`
 WHERE 1

Okey,这个查询工作得很好,但我需要在这样的地方添加变量:

WHERE `v` = 4

完整代码:

SELECT 
            Tab1.`name`,
            Tab1.`removed`,
            Raq.`removed`,
            Raq.`type`,
            (select `value` from `raq_add` where `raq_id` = `Tab1`.`raq_id` and `key` = 'v') as `v`

FROM `reservation` `Reservation`
            left join `tab1` `Tab1` on `Tab1`.`id` = `Reservation`.`tab1_id`
            left join `raq` `Raq` on `Raq`.`id` = `Tab1`.`raq_id`
 WHERE `v` = 4

我知道我应该将此变量添加到Select:

(select `value` from `raq_add` where `raq_id` = `Tab1`.`raq_id` and `key` = 'v' and `value` = 4) as `v`

但是value!= 4

的字段

它们显示为null,我根本不想显示它们或显示它们与v不同或value未显示

2 个答案:

答案 0 :(得分:1)

只需用另一个选择包装查询,然后您就可以在WHERE子句中按照它进行过滤:

SELECT * 
FROM (Your Query Here) t 
WHERE t.v = 4

答案 1 :(得分:1)

如果只想匹配的行使用Inner Join而不是left join

SELECT 
            Tab1.`name`,
            Tab1.`removed`,
            Raq.`removed`,
            Raq.`type`,
            (select `value` 
                from `raq_add` 
                where `raq_id` = `Tab1`.`raq_id` and `key` = 'v') as `v`

FROM `reservation` `Reservation`
            INNER join `tab1` `Tab1` on `Tab1`.`id` = `Reservation`.`tab1_id`
            INNER join `raq` `Raq` on `Raq`.`id` = `Tab1`.`raq_id`
 WHERE  (select `value` 
                from `raq_add` 
                where `raq_id` = `Tab1`.`raq_id` and `key` = 'v') = 4