在mySQL WHERE子句中使用LIKE

时间:2015-10-19 01:37:23

标签: mysql sql where-clause

我正在尝试使用以下查询选择名称包含 Christina 的数据,但它返回所有数据,而不仅仅是 Christina

SELECT a.id_transaksi, a.total_harga, (
        SELECT c.id_transfer
        FROM tbl_transfer c
        WHERE c.id_transaksi = a.id_transaksi
        ) AS id_transfer, (
        SELECT d.nama
        FROM tbl_costumer d
        WHERE d.username = a.username
        ) AS nama_costumer
FROM tbl_faktur a, tbl_transfer c, tbl_costumer d
WHERE a.konfirm_user = 1
    AND d.nama LIKE '%christina%'
GROUP BY a.id_transaksi
ORDER BY a.id_transaksi DESC

3 个答案:

答案 0 :(得分:2)

您不需要子查询。 join具有适当条件的表格应该有效。

SELECT
a.id_transaksi, a.total_harga,  
c.id_transfer id_transfer,
d.nama as nama_costumer
FROM tbl_faktur a 
JOIN tbl_transfer c on c.id_transaksi = a.id_transaksi
JOIN tbl_costumer d on d.username = a.username
WHERE a.konfirm_user = 1 
AND d.nama LIKE '%christina%'
ORDER BY a.id_transaksi DESC 

答案 1 :(得分:0)

您在顶级'上的唯一过滤器查询是c.id_transaksi = a.id_transaksi。您需要jointbl_costumer,然后对其进行过滤以查看您期望的结果。我不知道您的客户/转移表之间的关系,但可能customer_id tbl_transfer,这应该会带您到客户表。

答案 2 :(得分:0)

我找到了答案,只是将EXSIST添加到WHERE子句......

SELECT a.id_transaksi, a.total_harga, a.total_berat, a.kurir, a.servis, a.resi, a.konfirm_user, a.konfirm_admin, a.date_user, a.ongkir, (   
                SELECT  c.id_transfer
                FROM tbl_transfer c
                WHERE c.id_transaksi = a.id_transaksi
                ) AS id_transfer, (

                SELECT  d.nama
                FROM tbl_costumer d
                WHERE d.username = a.username
                ) AS nama_costumer, (

                SELECT  d.provinsi_asal
                FROM tbl_costumer d
                WHERE d.username = a.username
                ) AS provinsi_asal, (

                SELECT  d.kota_asal
                FROM tbl_costumer d
                WHERE d.username = a.username
                ) AS kota_asal, (

                SELECT  d.alamat
                FROM tbl_costumer d
                WHERE d.username = a.username
                ) AS alamat, (

                SELECT  d.tlp
                FROM tbl_costumer d
                WHERE d.username = a.username
                ) AS tlp

            FROM tbl_faktur a,  tbl_transfer c, tbl_costumer d
            WHERE a.konfirm_user=1 AND exists (SELECT d.nama from tbl_costumer d  where a.username=d.username and d.nama like '%$keyword%') 
            GROUP BY a.id_transaksi
            ORDER BY a.id_transaksi DESC