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

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.

Related

SQL Select the column if the value is like with multiple columns

I need to create a autocomplete search with ajax. The suggestions should only contain the 10 most entered results. The search query has to check multiple columns if the value is like my variable.
But my problem is to create the query and the php logic for that.
Is there any plugin or something simular for that?
How can I select a column if the value in it is like my variable?
I need to create a count query, which counts (in all columns) "how often is here the full word (splitted by spaces)" <- which is like the found one (to get the relevance)
At the end I need to sort the found entries by their relevance to provide the 10 most relevant entries.
(The real query checks for more columns than just 2, but for dummy reasons are 2 okay)
The query which selects the rows where the value is like...
select * from
(
(select department from entries where department like '%myVariable%')
OR
(select grade from entries where grade like '%myVariable%')
)
I think you know what I mean. Does anyone have any hints, suggestions, examples or useful links for me?
Thanks in advance!
Best regards,
FriaN
Why not use union all here?
select department from entries where department like '%myVariable%'
union all
select grade from entries where grade like '%myVariable%'
Then this should order the results for you:
select department, count(*) cnt from (
select department from entries where department like '%myVariable%'
union all
select grade from entries where grade like '%myVariable%')a
group by department
order by count(*) desc

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

SQL SELECT DISTINCT confusion

I know I can select distinct like this:
SELECT DISTINCT id, title, photo FROM myTable;
But when I want to SELECT id, title but with distinct title, what should I do?
I mean I want to select rows and avoid duplicate titles. Because maybe there be duplicate photos, but it's not important, I need only distinct titles. How then should I select photo and title fields and at the same time set title to be unique and distinct?
SELECT id, title, photo FROM myTable GROUP BY title;
simple select query with group by will work here.
Depends on your data, but basically you are looking to force photo to return a single value, along with your distinct title. Something like this:
SELECT title, MAX(photo)
FROM myTable
GROUP BY title
would do that, for example.
Distinct Photo Menas all photo without no repetition
SELECT id, photo FROM myTable GROUP BY title;

mysql - search results - multiple tables

I want to write a query to search in multiple tables (news, articles, projects, files)
While searching I found this
SELECT title, post FROM news WHERE MATCH (title,post) AGAINST ('press');
I tested it and it's working, but i failed to extend this to multiple tables.
How to write one query that return me search results for multiple tables ?
One method is to use a union:
SELECT title, post FROM news WHERE MATCH (title,post) AGAINST ('press')
UNION
SELECT title, post FROM articles WHERE MATCH (title,post) AGAINST ('press')
UNION
SELECT title, post FROM projects WHERE MATCH (title,post) AGAINST ('press')
UNION
SELECT title, post FROM files WHERE MATCH (title,post) AGAINST ('press')
This now essentially becomes one pseudo table with all of the records merging into one dataset.
This is one way to do it. I'm not sure what Match does, but in the where you can also your Match function
Select Table1.Title, Table2.Post FROM Table1, Table2 WHERE Table1.Title = 'press' AND Table2.Title = 'press'
This query will give you the Title and the Post of the 2 tables that have both have press in it.
Have a look on this query , you may use like this -
SELECT *
FROM news t1, articles t2, projects t3, files t4 WHERE MATCH ( t1.title, t1.post)
AGAINST ('press') or Match(t2.title,t2.post) AGAINST('press')
and set all column you want to search set in MATCH() function.
You could try this, it may helpful for you.

How can I select mysql data with a union statement where the data matches each select statement, i.e. combine the AND operator with UNION?

Lets say I have a table with just two columns: name and mood. A row holds a persons name, and their mood, if they have multiple moods, then multiple rows are stored in the DB.
For example, in the database is John, who is happy, excited, and proud.
This is represented as
John Happy
John Excited
John Proud
What I want to do is select the name based on several moods being met. Similiar to the UNION:
SELECT name WHERE mood=Happy
UNION
SELECT name WHERE mood=Excited
UNION
SELECT name WHERE mood=Proud
However using the above union would result in:
John
John
John
Union all would result in one single result of John, but it would also select any names that only match one of the queries.
I can think of a few algorithms which would take each individual mysql_result resource (I'm using PHP), and look for matching results, but what I want to know is whether MySQL already facilitates this.
I realise the above is quite a vague generalisation, needless to say my actual program is alot more complicated and I've dumbed it down a little for this question, please don't hesitate to ask questions.
Provided you have no duplicates, you can do it with a subquery:
SELECT `name` FROM (
SELECT `name`, COUNT(*) AS `count` FROM `moods`
WHERE `mood` IN ('Excited', 'Happy', 'Proud') GROUP BY `name`
) WHERE `count` = 3
Alternatively, you can use join:
SELECT `m1`.`name` FROM `moods` `m1`
JOIN `moods` `m2` USING (`name`)
JOIN `moods` `m3` USING (`name`)
WHERE `m1`.`mood` = 'Excited' AND `m2`.`mood` = 'Happy' AND `m3`.`mood` = 'Proud'
Not so cute, but might be faster if you use LIMIT. Or maybe not. Depends a lot on query planner.
UPD: thanks to Tudor Constantin for reminding me about HAVING, the first query can then be:
SELECT `name` FROM `moods`
WHERE `mood` IN ('Excited', 'Happy', 'Proud')
GROUP BY `name`
HAVING COUNT(*)>3
Replace UNION with INTERSECT .
your query is already correct. you can ADD an extra column using you searched word in the WHERE clause.
SELECT name,'Happy' as imood WHERE mood='Happy'
UNION
SELECT name,'Excited' as imood WHERE mood='Excited'
UNION
SELECT name,'Proud' as imood WHERE mood='Proud'
If I understand your question correctly, I think in this case you don't actually need a UNION but just multiple conditions in a WHERE statement.
Try this:
SELECT name, mood FROM myTable WHERE mood in ('Happy','Excited','Proud')
This should give the result:
John, Happy
John, Excited
John, Proud
If you don't care about getting multiple results for mood, try this:
SELECT DISTINCT name FROM myTable WHERE mood in ('Happy','Excited','Proud')
Which will just give:
This should give the result:
John
Updated
If you want to match ALL the conditions, you'd probably have to use subselects:
SELECT DISTINCT name FROM myTable
WHERE name IN
(SELECT name FROM myTable WHERE mood = 'Happy')
AND name IN
(SELECT name FROM myTable WHERE mood = 'Excited')
AND name IN
(SELECT name FROM myTable WHERE mood = 'Proud')
Try with:
SELECT name FROM user_moods um1
INNER JOIN user_moods um2 ON um1.name = um2.name
WHERE um1.mood IN ('Happy','Excited','Proud')
GROUP BY um2.mood
HAVING COUNT(um2.mood) = 3 # the number of different moods

Categories