我有2个具有以下结构的表:
Custom Pricing List
+------------+--------------+------------ +
| stock_code | stored_price | pricing_ref |
+------------+--------------+------------ +
Generic Pricing List
+------------+---------------------+--------------+-------------+--------------+
| stock_code | last_purchase_price | sales_price | description | qty_in_stock |
+------------+---------------------+--------------+-------------+--------------+
我想要返回的内容如下:
+------------+---------------------+--------------+--------------+-------------+
| stock_code | last_purchase_price | sales_price | description | qty_in_stock |
+------------+---------------------+--------------+--------------+-------------+
目前我只使用以下MySQL语句查询最后一个表:
SELECT * FROM $table WHERE $column LIKE '%$term%' $or LIMIT 0,10
但是,我想合并2,仍然可以在stock_code
列上进行通配符搜索。
所有结果必须返回description
和qty_in_stock
。结果中的sales_price
将来自stored_price
的{{1}}或来自Custom Pricing Table
的{{1}},但sales_price
优先于Generic Pricing Table
来自stored_price
。
我知道我需要进行UNION查询,但我不确定如何编写它。
使用声明:
sales_price
我现在收到以下错误:
Generic Pricing Table
答案 0 :(得分:1)
我认为你可以加入这两个表格。试试这个:
SELECT
generic.stock_code,
generic.last_purchase_price,
IFNULL(custom.stored_price, generic.sales_price) AS actual_price,
generic.description,
generic.qty_in_stock
FROM
Generic_Pricing_List generic
JOIN Custom_Pricing_List custom
on custom.stock_code = generic.stock_code
WHERE $column LIKE '%$term%' $or LIMIT 0,10;
如果stored_price不为null且已定义,则会将其拾取。否则,将收取sales_price。
答案 1 :(得分:0)
SELECT t1.*, t2.field1, t2.field2
FROM $table1 AS t1
LEFT JOIN $table2 AS t2 ON (t1.stock_code = t2.stock_code)
WHERE t1.$column LIKE '%$term%' $or
LIMIT 0,10
只需使用JOIN
答案 2 :(得分:0)
1.42857143
将为您提供font-size
的所有行以及来自Left Inner Join
的匹配行。
Generic_Pricing_List
答案 3 :(得分:0)
SELECT g.*
FROM Generic_Pricing_List g
LEFT JOIN Custom_Pricing_List c
ON g.stock_code = c.stock_code
WHERE g.Search_Column LIKE '%Term%'
LIMIT 0,10
答案 4 :(得分:0)
您可以使用联盟,但不是必需的。但是,对于较大的数据集,联合可能更有效,因为"如果" s可能很昂贵。又快又脏:
SELECT gpl.stock_code, last_purchase_price, if(stored_price is null, sales_price, stored_price) as sales_price, description, qty_in_stock
FROM Generic_Pricing_List gpl
LEFT JOIN Custom_Pricing_List cpl
ON gpl.stock_code = cpl.stock_code
AND cpl.stored_price != ''
AND cpl.stored_price IS NOT NULL
WHERE $column LIKE '%$term%' $or
LIMIT 0,10
使用联盟:
SELECT * FROM
(SELECT gpl.stock_code, last_purchase_price, stored_price as sales_price, description, qty_in_stock
FROM Generic_Pricing_List gpl
JOIN Custom_Pricing_List cpl
ON gpl.stock_code = cpl.stock_code
AND cpl.stored_price != ''
AND cpl.stored_price IS NOT NULL
WHERE $column LIKE '%$term%' $or
UNION
SELECT gpl.stock_code, last_purchase_price, sales_price, description, qty_in_stock
FROM Generic_Pricing_List gpl
WHERE $column LIKE '%$term%' $or) foo
GROUP BY foo.stock_code
LIMIT 0,10
小心"或"注入语句,因为它可能会导致结果出现问题。