I'm working with some MySQL tables that have a not so friendly structure.
Currently I have a query like the following:
$query = 'SELECT textID, subject FROM articles
WHERE (UPPER(subject) LIKE "%'.$string.'%") AND status = "1"
ORDER BY CASE WHEN subject LIKE "'.$search.' %" THEN 0
WHEN creator LIKE "'.$search.'%" THEN 1
WHEN email LIKE "'.$search.'%" THEN 2 ELSE 3 END,
subject LIMIT 10';
I then obviously run and get the results like so:
$res = $db->query($query);
$result = array();
while($results = $res->fetch_assoc()) {
$result[] = $results;
}
Now that I've pulled the data from the database, I now need to match it against data from a second table so that I can get/use only the results that match.
I want to now run the above array, specifically the "textID" retrieved for each result, against a second table to only use the results from the array that match the "textID" in a second table.
For example: Let's say the above query returned the following (NOTE: these results will be dynamic based on the "string" used in the query):
Table: articles
textID ----- Subject
1 | Test
4 | Test 2
25 | Test 3
33 | Test 4
51 | Test 5
I want to run a second query (or implement it into the original query) that matches the "textID" up against any entries in a second table that share the same textID.
So if the second MySQL table has the following matching textID's:
Table: altarticles
textID
1
25
51
I'd want to scrap the original "$result[]" and create a new array that only contains the matching results:
textID ----- Subject
1 | Test
25 | Test 3
51 | Test 5
How would one go about doing this?
This should be accomplished easily by using a JOIN clause. JOIN altarticles
on the TextID field. Alias each table articles a
and altarticles aa
and SELECT
the aa.subject
instead of the original table's subject.
A regular JOIN is also called an inner join meaning that only the rows match for the conditions for both tables are displayed.
$query = '
SELECT
a.textID,
a.subject
FROM articles a
JOIN altarticles aa ON (a.textID = aa.textID)
WHERE
(UPPER(a.subject) LIKE "%'.$string.'%")
AND a.status = "1"
ORDER BY CASE
WHEN a.subject LIKE "'.$search.' %" THEN 0
WHEN a.creator LIKE "'.$search.'%" THEN 1
WHEN a.email LIKE "'.$search.'%" THEN 2
ELSE 3 END, a.subject
LIMIT 10
';
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.