English 中文(简体)
使用LIKE语句时,如何根据另一个表的计数更新表
原标题:How can i update a table based on a count of another table while using LIKE statement

我知道如何使用t1.id=t2.id等从另一个表的计数更新一个表字段。但我有一些典型的问题。我必须在WHERE子句中使用LIKE语句。

这也是我想做的类似的事情。

UPDATE `CATEGORIES`
SET    `num_listings` = (SELECT COUNT(*)
                         FROM   `LISTINGS`
                         WHERE  `LISTINGS`.`CATEGORY` LIKE
                                ws_concat(  , "%-", `CATEGORIES`.`ID`, "-%"));  

(示例:我在LISTINGS表中将CATEGORY存储为-25-作为字段名CATEGORY)

我知道我不能在这里使用ws_contact,但有其他方法可以实现吗?

提前谢谢。

问题回答

除非有充分的理由使类别ID仅由列表表中字符串的一部分表示,否则处理这种数据结构的最佳方法是向listings表添加一个category_ID列,并确保在添加或编辑列表时正确填充该列。

这将允许简单地JOIN这两个表ON categories.id=listings.category_id,并且更有意义。到目前为止,这也将提供更好的性能。

如果您确实想保持DB结构不变,可以使用一个带有LIKE和CONCAT的临时表:

DROP TABLE IF EXISTS temp;

CREATE TABLE temp AS 
       SELECT categories.id, COUNT(*) AS c
       FROM categories
       JOIN listings ON listings.category LIKE CONCAT( % ,categories.id, % )
       GROUP BY categories.id;

UPDATE categories, temp
SET categories.num_listings = temp.c
WHERE categories.id = temp.id;




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签