简体   繁体   中英

Extract a sum of table1.column2 where table1.column1 contains value from table2.column2

I'm trying to build a database similar to the structure in the picture

目标

I tried using this code but it doesn't seem to work.

 SELECT wp_wpdatatable_4.remaining, wp_wpdatatable_7.name
    FROM wp_wpdatatable_4
    INNER JOIN wp_wpdatatable_7
        ON wp_wpdatatable_7.name LIKE CONCAT(wp_wpdatatable_4.techsname, '%');

Can anyone help?

Use wildcards on wp_wpdatatable_7.name:

SELECT wp_wpdatatable_4.remaining, wp_wpdatatable_7.name
FROM wp_wpdatatable_4
INNER JOIN wp_wpdatatable_7 
ON wp_wpdatatable_4.techsname like '%wp_wpdatatable_7.name%'

You are close, just interchange the field names.

You are trying to query John Smith LIKE 'John Smith CTE 555-555-5555%' which will never be true.

This will be true John Smith CTE 555-555-5555 LIKE 'John Smith%'

Here is corrected query

SELECT wp_wpdatatable_4.remaining, wp_wpdatatable_7.name
FROM wp_wpdatatable_4
INNER JOIN wp_wpdatatable_7
ON wp_wpdatatable_4.techsname LIKE CONCAT(wp_wpdatatable_7.name, ' %');

Note: added space before % to ensure word match

Update

To sum values in remaining column, use GROUP BY . Here is the updated query:

SELECT SUM(wp_wpdatatable_4.remaining) AS total_remaining, wp_wpdatatable_7.name
FROM wp_wpdatatable_4
INNER JOIN wp_wpdatatable_7
ON wp_wpdatatable_4.techsname LIKE CONCAT(wp_wpdatatable_7.name, ' %')
GROUP BY wp_wpdatatable_7.name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM