How do I look at column of syscolumns in sybase? - sap-iq

I am trying to get schema of existing database using this query in sybase iq 15.4 -
SELECT t.name AS TABLE_NAME, col.name AS column_name
FROM sysobjects t
JOIN syscolumns col ON t.id=col.id
WHERE t.TYPE='U'
I am getting an error "syscolumns is ambigous" so I resolved this error by changing the syntax -
SELECT t.name AS TABLE_NAME, col.name AS column_name
FROM sysobjects t
JOIN sys.syscolumns col ON t.id=col.id
WHERE t.TYPE='U'
After that I am getting an error "Column id not found". Can you please help me to use this query to get the column for join on other column.
Thanks In Advance!!

We can use this query as -
SELECT t.name AS TABLE_NAME, col.cname AS column_name
FROM sysobjects t
JOIN sys.syscolumns col ON t.name =col.tname
WHERE t.TYPE='U'

Related

Find n most referenced records by foreign_key in related table

I have a table skills and a table programs_skills which references skill_id as a foreign key, I want to retrieve the 10 most present skills in table programs_skills (I need to count the number of occurrence of skill_id in programs_skills and then order it by descending order).
I wrote this in my skill model:
def self.most_used(limit)
Skill.find(
ActiveRecord::Base.connection.execute(
'SELECT programs_skills.skill_id, count(*) FROM programs_skills GROUP BY skill_id ORDER BY count DESC'
).to_a.first(limit).map { |record| record['skill_id'] }
)
end
This is working but I would like to find a way to perform this query in a more elegant, performant, "activerecord like" way.
Could you help me rewrite this query ?
Just replace your query by:
WITH
T AS
(
SELECT skill_id, COUNT(*) AS NB, RANK() OVER(ORDER BY COUNT(*) DESC) AS RNK
FROM programs_skills
GROUP BY skill_id
)
SELECT wojewodztwo, NB
FROM T
WHERE RNK <= 10
This use CTE and windowed function.
ProgramsSkills.select("skill_id, COUNT(*) AS nb_skills")
.group(:skill_id).order("nb_skills DESC").limit(limit)
.first(limit).pluck(:skill_id)

how codeigniter join two tables to have both Id columns

I want to join two tables that I have both Id columns in join table by codeigniter.
I want both id column from comment and users tables
I write below code
$this->db->select('users.name as user_full_name, users.id as userid', false);
$this->db->from('users');
$this->db->select()
->from('comment')
->where('project_id', $projectId)
->where('user_id', $user_id)
->join('users', 'comment.user_id_from =userid')
->order_by("comment.id", "asc");
return $this->db->get()->result_array();
but face error, I do not know why
error:
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM (users, comment) JOIN users ON comment.user_id_from =userid W' at line 1
SELECT users.name as user_full_name, users.id as userid, * FROM (users, comment) JOIN users ON comment.user_id_from =userid WHERE project_id = '3' AND user_id = '84' ORDER BY comment.id ASC
please show me how to solve it
try this:
$this->db->select('*,comment.id as comment_id,users.user_id as user_id,users.name as user_name');
$this->db->from('comment');
$this->db->where('user_id', $user_id);
$this->db->join('users', 'users.user_id = comment.id');
$this->db->order_by("comment.id", "asc");
return $this->db->get()->result_array();
it return all user and comment table data
may be this codeigniter query help you out

Postgresql INNER JOIN with multiple conditons

I am working on a query that is driving me nuts. I am trying to search a table by the values in a join table. Currently, the query is returning all results that have either of the specified ids. I would only like it to return records that only have both of the ids.
Here is my table setup
creat_table champions do |t|
t.integer :id
end
create_table champions_champion_combinations do |t|
t.integer :champion_id
t.integer :champion_combination_id
end
create_table champion_combinations do |t|
t.integer :id
end
Here is the query as I have it
SELECT
champion_combinations.*
FROM champion_combinations
INNER JOIN champions_champion_combinations
ON champions_champion_combinations.champion_combination_id = champion_combinations.id
INNER JOIN champions
ON champions.id = champions_champion_combinations.champion_id
WHERE champions.id IN (1, 2)"
Generated from the RoR ActiveRecord query
ChampionCombination.joins(:champions).where(champions: {id:[1,2]})
So this returns all champion_combinations that have either champion ids 1 or 2 joined to it. What type of query do I need to write that only returns the combination with both ids 1 and 2 joined to it?
Thanks in advance.
If you're interesting in pure SQL solution, then you can use GROUP BY and HAVING clauses to achieve your goal. Here is the sql query:
SELECT cc.*
FROM champion_combinations AS cc
INNER JOIN champions_champion_combinations AS ccc ON ccc.champion_combination_id = cc.id
WHERE ccc.champion_id IN (1, 2)
GROUP BY cc.id
HAVING array_agg(ccc.champion_id) #> ARRAY[1,2];
PS Thanks to #IgorRomanchenko for great suggestions.
It is not inner join problem. Inner join is working as expected. SQL query given above doing inner join of both the tables with "champion_combination", there is no restriction which says both ids has to be present. You should do is
ChampionCombination.joins(:champions).where(champions: {id:[1,2]}).where("champion_id is not null and compion_combination_id is not null")

Nested query in squeel

Short version: How do I write this query in squeel?
SELECT OneTable.*, my_count
FROM OneTable JOIN (
SELECT DISTINCT one_id, count(*) AS my_count
FROM AnotherTable
GROUP BY one_id
) counts
ON OneTable.id=counts.one_id
Long version: rocket_tag is a gem that adds simple tagging to models. It adds a method tagged_with. Supposing my model is User, with an id and name, I could invoke User.tagged_with ['admin','sales']. Internally it uses this squeel code:
select{count(~id).as(tags_count)}
.select("#{self.table_name}.*").
joins{tags}.
where{tags.name.in(my{tags_list})}.
group{~id}
Which generates this query:
SELECT count(users.id) AS tags_count, users.*
FROM users INNER JOIN taggings
ON taggings.taggable_id = users.id
AND taggings.taggable_type = 'User'
INNER JOIN tags
ON tags.id = taggings.tag_id
WHERE tags.name IN ('admin','sales')
GROUP BY users.id
Some RDBMSs are happy with this, but postgres complains:
ERROR: column "users.name" must appear in the GROUP BY
clause or be used in an aggregate function
I believe a more agreeable way to write the query would be:
SELECT users.*, tags_count FROM users INNER JOIN (
SELECT DISTINCT taggable_id, count(*) AS tags_count
FROM taggings INNER JOIN tags
ON tags.id = taggings.tag_id
WHERE tags.name IN ('admin','sales')
GROUP BY taggable_id
) tag_counts
ON users.id = tag_counts.taggable_id
Is there any way to express this using squeel?
I wouldn't know about Squeel, but the error you see could be fixed by upgrading PostgreSQL.
Some RDBMSs are happy with this, but postgres complains:
ERROR: column "users.name" must appear in the GROUP BY clause or be
used in an aggregate function
Starting with PostgreSQL 9.1, once you list a primary key in the GROUP BY you can skip additional columns for this table and still use them in the SELECT list. The release notes for version 9.1 tell us:
Allow non-GROUP BY columns in the query target list when the primary
key is specified in the GROUP BY clause
BTW, your alternative query can be simplified, an additional DISTINCT would be redundant.
SELECT o.*, c.my_count
FROM onetable o
JOIN (
SELECT one_id, count(*) AS my_count
FROM anothertable
GROUP BY one_id
) c ON o.id = counts.one_id

schema does not exist error with Postgresql and Texticle

I tried to configure Texticle and ran into this error on migration. Error msg is referring to the line I marked with <<<<
PGError: ERROR: schema "half_links" does not exist
: CREATE VIEW searches AS
SELECT items.id AS searchable_id, items.name AS term,
CAST('Item' AS varchar) AS searchable_type
FROM items
UNION
SELECT half_links.id AS searchable_id, half_links.item.name AS term, <<<<
CAST('HalfLink' AS varchar) AS searchable_type
FROM half_links
This is my migration
class CreateSearches < ActiveRecord::Migration
def self.up
ActiveRecord::Base.connection.execute <<-SQL
CREATE VIEW searches AS
SELECT items.id AS searchable_id, items.name AS term,
CAST('Item' AS varchar) AS searchable_type
FROM items
UNION
SELECT half_links.id AS searchable_id, half_links.item.name AS term,
CAST('HalfLink' AS varchar) AS searchable_type
FROM half_links
SQL
end
and models
:half_link belongs_to :item
:item has_many :half_links
Im running this on my localhost PSQL. How can I get around this?
The error is in the second select. half_links.item.name makes Postgres assume that half_links is a schema name (the correct syntax is ..)
Seeing how your associations are, I guess you mean to get the name of the items belonging to half_links.
Since Postgres have no idea on how the Rails associations works, you need to get the data yourself:
CREATE VIEW searches AS
SELECT items.id AS searchable_id, items.name AS term,
CAST('Item' AS varchar) AS searchable_type
FROM items
UNION
SELECT half_links.id AS searchable_id, items.name AS term,
CAST('HalfLink' AS varchar) AS searchable_type
FROM half_links join items on half_links.item_id = items.id
This is assuming that the foreign key in half_links to items are called item_id which it should be if you created the tables using Rails migration.
Additionally, this will only show the half_links that actually have an item associated to it, if there can be ones that don't have an item, then change the join to outer join. Term will in those cases be NULL.

Resources