SQL query on 3 tables, one with different column name - php

I have 3 tables;
projects, campaigns, clients.
I need to return results from all 3 tables where the searchterm matches. However, I need to check against 'name' column in projects and campaigns tables, but 'description' column in the clients table. NB This is an existing client database, I have no authority to change the the column names.
Example: user searches for 'data', I need to SELECT:
name as title FROM projects WHERE name LIKE %data%,
name as title FROM campaigns WHERE name LIKE %data%
AND
description as title FROM clients WHERE description LIKE %data%
I'm struggling to combine the queries. Below is what I have so far, which returns a syntax error. I am also thinking I may be taking the wrong approach.
SELECT
p.name,
c.name,
cl.description AS title
FROM
projects,
campaigns,
clients
WHERE
p.name LIKE % DATA %
OR c.name LIKE % DATA %
OR cl.description LIKE % DATA %

You are looking for union all:
SELECT name as title FROM projects WHERE name LIKE %data%,
UNION ALL
SELECT name as title FROM campaigns WHERE name LIKE %data%
UNION ALL
SELECT description as title FROM clients WHERE description LIKE %data%;
If you want to remove duplicates, then use UNION instead of UNION ALL.

Related

How to loop data from multiple tables in MySQL?

I have these tables with the following columns:
Article
1.1. title
1.2. text
1.3. sortnr
Congress
2.1. title
2.2. text
2.3. sortnr
And, obviously, others, but these are the ones that are the same. And what I'd like to do is write a query where I can then loop through these fields as if they were from one table.
What it looks like:
SELECT * FROM article, congress ORDER BY sortDate DESC LIMIT 3
but with that I can't use fields like title and so on because during the loop, all the, for example, title fields are being turned in to the ones from congress table.
Is there a way to mix the two tables and treat them like they were from one table considering that they aren't joined in any way?
Try this:
SELECT *, 'article' as tblnm FROM article
UNION
SELECT *, 'konferansenentry' as tblnm FROM konferansenentry
ORDER BY sortDate DESC
LIMIT 3
It will only work if both table have same field other wise you have to select individual one by one.

Finding records that contain keywords

I have two tables.
table 1 - with 500+ keywords
id
keyword
table 2
id
title
desc
content
...
I'm looking for best way to select all records from table 2, where title field contain one or more keywords from table 1. I think LIKE, REGEX isn't good choice due to performance. To first and the second table, I constantly add new records.
I would use concat and like like so:
SELECT * FROM table_2 AS t2
LEFT JOIN table_1 AS t1 ON t2.title LIKE CONCAT('%', t1.keyword, '%');
Check this SQL FIDDLE

Search multiple tables Mysql

I'm working on a advanced search functionality with php and mysql.
The tables are:
blogPost[id, title, description]
water[id, title, description,]
waterSpecie[id, waterId, specieId]
specie[id, name]
user[id, username]
What I want done is this:
The user will be able to search from a text field with a keyword, and the results should only be unique once.
For example:
The user searches for cod then I would like to show all the blogposts that has cod in there titles or description and all the waters that has cods in it and also if a user is nicked cod. But if let's say the blogPost has cod in its title and description I don't want it to show up twice in the results list.
But if only lets say the blogPost table has cod in its title I would only want to show that and nothing else.
I've managed to do it with this sql query: I would now like to add the blogPost table to that query and make it possible to search from it. So if only one table have cod I want to show only the result from that table.
SELECT DISTINCT W.lat, W.lng, W.municipalityId, W.title, W.description
FROM water AS W, specie AS S, waterSpecie AS WS
WHERE S.name LIKE '%$term%' AND W.id = WS.waterId AND S.id = WS.specieId
OR W.title LIKE '%$term%' AND W.id = WS.waterId AND S.id = WS.specieId;
I hope I've managed to explain my problem and hopefully I could get some help on this issue.
You might try this:
Select distinct tablename,id from
(select 'blogpost', as tablename, id, title as searchfield from blogpost
union
select 'blogpost' as tablename, id, description as searchfield from blogpost
union
select 'water' as tablename, id, description as searchfield from water
union
select 'specie' as tablename, id, name as searchfield from specie
union
select 'user' as tablename, id, username as searchfield from user) searcher
where searcher.searchfield='cod'
I don't exactly get what's going on with waterSpecie, so I've left it out.
You should get results something like:
tablename id
blogpost 5
user 12
And then you can query the database to get the record from blogpost with id=5, and the record from user with id=12.
You'll be able to do this programmatically in your PHP. And if you add a table that you want to add to the search functionality, you only have to do it by adding a UNION in the query below, rather than making a join and adding another piece to a WHERE clause.
I'm not sure that this would scale to Amazon.com size, so consult somebody better than me before you get that big.
You will be best served by simplifying your MySQL queries and combining results in your PHP code. The main reason for this in your case is that you want to combine dissimilar results - blog entries if they have the search term and/or waters and other things if they have the search terms.
In pseudo code, I'd do something like this (use a DAO in the real code, of course):
$foundposts = findblogposts($searchterm);
$foundusers = findusers($searchterm);
$foundwaters = findwaters($searchterm);
// etc
if($foundposts){
print($foundposts);
}
if($founduers){
print($foundusers);
}
if($foundwaters){
print($foundwaters);
}
// etc
That way, you can handle the different formatting requirements you probably have to show blog posts correctly, and users correctly, etc.

Searching multiple tables in query

SELECT DISTINCT business.name AS businessname
,business.description AS description
FROM business
, category
, sub_categories
WHERE business.cityID = '$city'
AND (category.name LIKE '%$name%'
OR sub_categories.name LIKE '%$name%')
AND business.status = 0
Pls the above SQL code is suppose to search a set of two tables the ones in the bracket and return the result, but for some reason, it's not doing so. What am i doing wrong?
Thank You.
Your query would produce a cartesian product. Depending on the size of your tables that could take a considerable amount of time.
Based on your clarification I'd use a subquery to check for matching categories, this way you don't have to use distinct in your query as it would only return each business once. I also suggest you to start with a decent SQL tutorial.
SELECT name AS businessname
,description AS description
FROM business
WHERE cityID = '$city'
AND status = 0
AND ( categoryID in (select id from category where name like '%$name%')
or subcategoryID in (select id from sub_categories where name like '%$name%')
)
Two things come to mind:
You are not joining any of the three tables together. Consider adding a few LEFT JOIN clauses.
You are selecting columns from only one table. If you wanted columns from other tables, you should add them to your SELECT clause.

Search in more than one table - give result as one column

Hey stackoverflow - This is my first question here.
I have 2 tables in my mySQLdb.
[tab_artist]
|id|artist|count
[tab_songtitle]
|id|songtitle|artistId
Im trying to select from both tab_artist.artist and tab_songtitle.songtitle as suggest where searchclause = m
I have tried this
SELECT artist, songtitle AS suggest
FROM tab_artist, tab_songtitle
WHERE artist LIKE('m%') OR songtitle LIKE('m%')
But this gives me 2 columns, artist and suggest
if the search is met i need artist to give me e.g. metallica.. but only once - but in songtitles i need all titles starting with met.
Hope this makes sence to the right expert :)
A union should do it:
select artist AS suggest from tab_artist WHERE artist LIKE 'm%'
union all
select songtitle AS suggest from tab_songtitle WHERE songtitle LIKE 'm%'
For this case, I would use union all so you won't get duplicates removed, but you may want this if, for example, Metallica has a self-titled album and you only want the word to appear once. In that case, union would be more appropriate.
You need a join:
Select artist, songtitle from tab_artist inner join tab_songtitle on tab_songtitle.artistID = tab_artist.ID where artist LIKe ('m%') OR songtitle like ('m%')
you want to use SQL UNION
select id, artist, count FROM table1
UNION
select id, title, artistid from table2
It basically concats the two result sets vertically. There are some restrictions and modifications, but generally thats all you need to do.
Use a UNION ALL to concatenate the results from the artist and song tables.
SELECT 'Artist' AS type, id, artist AS suggest
FROM tab_artist
WHERE artist LIKE 'm%'
UNION ALL
SELECT 'Song', id, songtitle
FROM tab_songtitle
WHERE songtitle LIKE 'm%'
Don't use UNION as some are suggesting as that will do a completely unnecessary (and expensive) DISTINCT on the query results.

Categories