在sqlite中搜索时,我使用以下SQL搜索所有列:
Select id from table where '--' || IFNULL(name, ' ')
|| '--' || IFNULL(created, ' ') || '--' || IFNULL(desc, ' ')
|| '--' LIKE '%query%'
现在我需要搜索order
表和order details
表。他们看起来像这样
订购表
id
date
customer_id
ORDER_DETAILS
id
product_id
cost
orders_id
qty
在这种情况下如何搜索,我尝试使用连接:
Select o.id,o.customer_id from orders o where '--'
(Select * from customers where name like '%query%' and id=customer_id) '--'
|| (Select * from product where name like '%query%' and ID =
(Select product_id from order_details where id =odetails_id)) '--' LIKE '%query%'
修改
我尝试了这个新查询,但我在' OR'
时收到错误消息SELECT o.id FROM orders o WHERE o.id in
((SELECT order_id FROM order_items WHERE order_items.service_id In
(SELECT id FROM services WHERE name like query))
OR o.id in
(SELECT order_id FROM order_items WHERE order_items.customer_id In
(SELECT id FROM customers WHERE name like query))
OR o.id in
(SELECT order_id FROM order_items WHERE order_items.cloth_id In
(SELECT id FROM cloths WHERE name like query) ))
我如何解决此问题
答案 0 :(得分:2)
您的查询包含一些错误:
假设缺少的表如下
create table product (id, name);
create table customers (id, name);
您的查询可以像这样修复
Select o.id,o.customer_id
from orders o
where '--' ||
( select name
from customers
where name like '%query%' and id=customer_id ) ||
'--' ||
( select name
from product
where name like '%query%' and
id = ( select product_id
from order_details
where id =odetails_id ) ) ||
'--'
LIKE '%query%';
但是,我建议你用连接替换你的标量子查询
select o.id, o.customer_id
from orders o
join customers c on o.customer_id = c.id
join order_details d on o.odetails_id = d.id
join product p on d.product_id = p.id
where c.name = '%query' and
p.name = '%query' and
'--' || c.name || '--' || p.name || '--' like '%query%';
修改强>
您的第二个查询有一个无关的括号。
SELECT o.id
FROM orders o
WHERE o.id in
( SELECT order_id
FROM order_items
WHERE order_items.service_id In
( SELECT id
FROM services
WHERE name like '%query%'))
OR o.id in
( SELECT order_id
FROM order_items
WHERE order_items.customer_id In
( SELECT id
FROM customers
WHERE name like '%query%'))
OR o.id in
( SELECT order_id
FROM order_items
WHERE order_items.cloth_id In
( SELECT id
FROM cloths
WHERE name like '%query%'));
但是,为清楚起见,您可以在子查询中推送OR:
SELECT o.id
FROM orders o
WHERE o.id in
( SELECT order_id
FROM order_items
WHERE order_items.service_id In
( SELECT id
FROM services
WHERE name like '%query%')
OR order_items.customer_id In
( SELECT id
FROM customers
WHERE name like '%query%')
OR order_items.cloth_id In
( SELECT id
FROM cloths
WHERE name like '%query%'));