【问题标题】:How to write query for comparing column having comma-separated values?如何编写查询以比较具有逗号分隔值的列?
【发布时间】:2012-12-28 13:15:07
【问题描述】:

我正在使用 Joomla 2.5。我正在使用 MYSQL 数据库。 我有一张表job_field,其中包含以下列:

cat_id  |  location_id
-----------------------
 1,4    |   66,70

我需要和另一个表比较job_value

cat_id  |  location_id | name
--------------------------------
 1      |   70         | Atul
 4      |   70,80      | Amit
 4      |   80,66      | Amol
 1      |   66         | Pritam    
 3      |   70         | Rahul
 2      |   66,90      | Ajit
 1      |   74         | Raju
 4      |   65,22      | Manoj

我希望输出将第一个表 job_details 中的 cat_idlocation_id 列与第二个表 job_valuecat_idlocation_id 进行比较。

它将检查第一个表 (job_details) 中的每个值,即 location_id 列值 (66, 70) 和第二个表 (job_value) location_id 列。我将输出数组作为

  Array (
    1 70     Atul
    4 70,80  Amit
    4 80,66  Amol
    1 66     Pritam
 )

【问题讨论】:

  • 你使用的是什么关系型数据库?
  • 这不是一个规范化的结构。基本上:你注定要失败——除非你重新考虑结构。
  • 在特定的 sql 语言方言中?是否只有一个或两个用逗号分隔的值?
  • 它将location_id的多个值存储在表中,因此很复杂

标签: php mysql sql joomla2.5


【解决方案1】:

这是一个badbadbad结构。即使问题可以解决,也不应该解决。它会很慢,而且无法维护。

应该为 DB 的这一部分创建类似以下内容的东西,而不是糟糕的结构:

CREATE TABLE PERSON (
    person_id BIGINT,
    name VARCHAR(64),
    PRIMARY KEY (person_id)
);

CREATE TABLE LOCATION (
    location_id BIGINT,
    name VARCHAR(64),
    PRIMARY KEY (location_id)
);
CREATE TABLE CAT (
    cat_id BIGINT,
    name VARCHAR(64),
    PRIMARY KEY (cat_id)
);

CREATE TABLE CAT_LOCATION (
    cat_id BIGINT,
    location_id BIGINT,
    PRIMARY KEY (cat_id,location_id),
    FOREIGN KEY (cat_id) REFERENCES cat(cat_id),
    FOREIGN KEY (location_id) REFERENCES location(location_id)
);

CREATE TABLE CAT_LOCATION_PERSON (
    cat_id BIGINT,
    location_id BIGINT,
    person_id BIGINT,
    PRIMARY KEY (cat_id,location_id,person_id),
    FOREIGN KEY (cat_id) REFERENCES cat(cat_id),
    FOREIGN KEY (location_id) REFERENCES location(location_id),
    FOREIGN KEY (person_id) REFERENCES person(person_id)
);

然后通过简单的连接得到你想要的东西比简单的容易:

SELECT cl.cat_id, cl.location_id, p.name
FROM CAT_LOCATION cl 
JOIN CAT_LOCATION_PERSON clp on cl.cat_id = clp.cat_id and cl.location_id=clp.location_id
JOIN PERSON p on clp.person_id = p.person_id

(我拒绝编写一个查询,该查询将以指定格式提供输出,数值用逗号分隔......(尽管可以通过 MySQL 的 GROUP_CONCAT 功能轻松实现)

【讨论】:

    【解决方案2】:

    试试这个 ::

    SELECT 
    * 
    FROM table1
    JOIN table2  ON FIND_IN_SET(table1.location_id, table2.location_id) > 0
    

    你也可以参考 Comma separated values in MySQL "IN" clause

    【讨论】:

    • 这个返回空结果集
    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 2020-03-08
    • 2023-03-16
    • 2020-02-01
    • 2011-06-18
    相关资源
    最近更新 更多