How to loop data from multiple tables in MySQL? - php

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.

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

SQL query on 3 tables, one with different column name

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.

SQL get data from multiple tables

I have 3 tables, all with some kind of articles: articles, columns and reports. All tables have a column called date, which contains the Unix timestamp when the record was added.
Now, I want to get the 50 most recently added records of the articles, columns and reports table and list them on a webpage. Because an article and a column can have the same unique ID, it is also necessary to know which result came from which table, for linking to the complete article (www.webpage.com/article/12 or www.webpage.com/column/12 for instance).
What is the best way to achieve this?
Frankly, the best way is probably to pull the elements into different variables. Anyway, here's an alternative if you want to do it all at once:
SELECT a.date, a.title, 'ARTICLE' category
FROM articles a
WHERE date > :date
UNION ALL
SELECT date, title, 'COLUMN' category
FROM columns
WHERE date > :date
UNION ALL
SELECT date, title, 'REPORT' category
FROM reports
WHERE date > :date
Something like that, anyway. The idea is that you can include a flag referencing the source table in each sub-select statement.

Order results from one MySQL table by another, which is saving multiple values into the order field

I'm trying to solve a MySQL problem, I have two tables:
CATEGORIES (COLUMNS: _id, _name)
POSTS (COLUMNS: _id, _category, _title, _text)
_category field in POSTS is LONGTEXT and can have multiple CATEGORIES _ID's separated only by , using implode(",") PHP function.
I try to list with PHP the 10 most popular categories, and to display in () the posts in them, but without luck.
I'm not very familar with MySQL, I only know how to use SELECT FROM WHERE ORDER LIMIT, INSERT & UPDATE so I will be very happy if someone can give me a good solution. I tried to use IN() but IN() needs the _category field of POSTS to be like this '1','2','3','4', now its 1,2,3,4 without the quotes, so if anyone know how I can transform this field into list without FIELD TYPE SET, I will be pretty happy.
You may want to change your relation model to the following:
Table CATEGORIES with columns:
_id
_name
Table POSTS with columns:
_id
_title
_text
Table POSSESS with columns:
post_id (FOREIGN KEY)
category_id (FOREIGN KEY)
A tuple in POSSESS relation (table) means the post_id is in the category_id category.
the key word for this is "many-to-many" relations, if possible refactor your scheme like Mark Baker wrote.
Using the model that Dyin suggested, you would then use something like this to list the top 10 categories by popularity (assuming that the more posts a category has, the more popular it is):
SELECT
c.*, # get all values for rows in categories
count(p.post_id) AS post_count # here we are counting the posts for each category using a field alias for the count
FROM (
categories AS c, # we are aliasing the tables also to shorten the typing a bit
possess AS p # you could also use aliases to join the same table multiple times
)
WHERE
c.id = p.category_id # link the categories and the possess tables
GROUP BY c.id # without this, the query would just count all posts, this way the result set is separated into groups by category
ORDER BY post_count DESC
LIMIT 10
Given what you said about your experience with SQL, this query might seem a bit over the top for now, but I think you could use as a starting point for learning more, as always, google is your friend. Start by researching how to link tables using foreign keys and joins.
I've used this:
SELECT *, (SELECT COUNT(*) FROM offer WHERE FIND_IN_SET(type._id, offer._type)) AS _count FROM type ORDER BY _count DESC LIMIT 0, 10
Works fine for now, its table type (columns: _id, _name) and offer (columns: .., .., _types,

Mysql syntax using IN help!

i have a pictures table : pictures(articleid,pictureurl)
And an articles table : articles(id,title,category)
So, briefly, every article has a picture, and i link pictures with article using articleid column. now i want to select 5 pictures of articles in politic category.
i think that can be done using IN but i can't figure out how to do it.
Note: Please only one query, because i can do it by selecting articles firstly then getting the pictures.
Thanks
To get five pictures from articles in a category you could do this:
SELECT pictures.pictureurl
FROM articles, pictures
WHERE articles.id = pictures.articleid AND articles.category = 'politic'
ORDER BY [your sort criteria]
LIMIT 5;
You could consider rephrasing the question a bit.
If you are looking for an IN query instead of a JOIN this is an alternative to Alex's query:
SELECT pictureurl
FROM pictures
WHERE arcticleid IN (SELECT id FROM articles WHERE category='politic')
LIMIT 5
Rewritten for clarification (see comments):
If you like to keep your JOIN criteria separated from your SELECT criteria, you can write something like the below:
SELECT pictureurl
FROM pictures
JOIN articles ON id = articleid
WHERE category LIKE 'politics'
ORDER BY RAND()
LIMIT 5
I find the intent slightly clear when it's written like that, and maybe it's just me, but I have encountered complex queries written in the SELECT * FROM a, b, c form that worked under MySQL 4 which choke MySQL 5, whereas the above format works fine with both.
Also, if you use uniform ID column names for conformity, and to avoid confusing yourself in more complex scenarios, you can use the USING clause instead. So if articles ID column is also named articlesid, the JOIN could be written like so:
SELECT pictureurl
FROM pictures
JOIN articles USING (articleid)
...
You don't really need to use IN for this. IN serves when you nest queries or when you have a known set of values to check against.
To select 5 random images in the politics category:
SELECT pictureurl FROM articles, pictures WHERE pictures.articleid = articles.id AND articles.category = 'politics' ORDER BY RAND() LIMIT 5

Categories