Hii我想在单个查询中使用不同条件从同一列中获取值两次
这是我的代码
SELECT
o.products_options_name,
ov.products_options_values_name AS products_options_values_name,
a.options_values_quantity
FROM
table_products_options o,
table_products_attributes a
WHERE
a.options_id = o.products_options_id
AND
o.products_options_values_id = a.options_values_id
AND
a.products_id = :products_id
AND
a.options2_values_id = options2_values_id
我想再次使用不同的条件获取列products_options_values_name的值,例如同一查询中的a.options2_values_id = ov.products_options_values_id。我怎么能这样做?
答案 0 :(得分:0)
尝试使用UNION运算符
SELECT o.products_options_name, ov.products_options_values_name AS products_options_values_name,
a.options_values_quantity
FROM
table_products_options o, table_products_attributes a
WHERE
a.options_id = o.products_options_id AND ov.products_options_values_id = a.options_values_id
AND a.products_id = :products_id1 AND
a.options2_values_id = options2_values_id
UNION
SELECT o.products_options_name, ov.products_options_values_name AS products_options_values_name,
a.options_values_quantity
FROM
table_products_options o, table_products_attributes a
WHERE
a.options_id = o.products_options_id AND ov.products_options_values_id = a.options_values_id
AND a.products_id = :products_id2 AND
a.options2_values_id = options2_values_id
答案 1 :(得分:0)
Union / Union都是最好的
喜欢
select o.products_options_name, ov.products_options_values_name as
products_options_values_name, a.options_values_quantity
from
table_products_options o, table_products_attributes a
where
a.options_id = o.products_options_id and ov.products_options_values_id =
a.options_values_id and a.products_id = :products_id and a.options2_values_id =
options2_values_id
UNION
select o.products_options_name, ov.products_options_values_name as products_options_values_name, a.options_values_quantity
from
table_products_options o, table_products_attributes a
where Diffrent Clause
Union Works就像Distinct一样,如果你的子句都返回值,则Union ALL将返回重复值。
或者在where子句and (a.b = c.d OR c.d=b.a) and
答案 2 :(得分:0)
您可以在on
子句中指定所需的条件。 on
条款?您的查询应使用显式join
语法。
以下是表达所需查询的一种方法:
select o.products_options_name, ov.products_options_values_name as products_options_values_name,
a.options_values_quantity
from table_products_options o join
table_products_attributes a
on a.options_id = o.products_options_id and
(ov.products_options_values_id = a.options_values_id or
a.options2_values_id = options2_values_id
)
where a.products_id = :products_id;